package com.shqcjd.preinstallmobile.helper.interceptor;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.adapter.Call;
import com.orhanobut.logger.Logger;
import com.shqcjd.preinstallmobile.api.HttpUrl;
import com.shqcjd.preinstallmobile.app.AppConstant;
import com.shqcjd.preinstallmobile.app.MyApp;
import com.shqcjd.preinstallmobile.helper.JsonConvert;
import com.shqcjd.preinstallmobile.model.ResponseData;
import com.shqcjd.preinstallmobile.model.pojo.LoginBean;
import com.shqcjd.preinstallmobile.util.PrefUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * user：lqm
 * desc：token验证令牌失效拦截器，token过期时刷新token或弹dialog跳转到登录界面
 * src:https://www.jianshu.com/p/62ab11ddacc8
 */

public class TokenInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request.Builder request = chain.request().newBuilder();
        String token = PrefUtils.getString(MyApp.getmContext(), AppConstant.TOKEN_KEY, "-1");
        //添加默认的Token请求头
        request.addHeader("token", token);

        Response proceed = chain.proceed(request.build());
        MediaType mediaType = proceed.body().contentType();
        String content = proceed.body().string();
        if (mediaType == null) {
            Request newRequest = chain.request().newBuilder()
                    .build();
            return chain.proceed(newRequest);
        }
        //如果token过期 再去重新请求token 然后设置token的请求头 重新发起请求 用户无感

        if (!mediaType.toString().equals("text/html") && isTokenExpired(content)) {
//            EventBus.getDefault().post(new FinishActivityEvent());
//
//            /*-------刷新token-------*/
            String newToken = getNewToken();
            if (newToken == null) {
                newToken = "";
            }
            PrefUtils.setString(MyApp.getmContext(), AppConstant.TOKEN_KEY, newToken);
            //使用新的Token，创建新的请求
            Request newRequest = chain.request().newBuilder()
                    .addHeader("token", newToken)
                    .build();
            return chain.proceed(newRequest);
//            return proceed;
        }
        return proceed.newBuilder()
                .body(ResponseBody.create(mediaType, content))
                .build();

    }

    private String getNewToken() {
        ResponseData<LoginBean> newToken = null;
        String user_account = PrefUtils.getString(MyApp.getmContext(), PrefUtils.USER_ACCOUNT, "");
        String user_pwd = PrefUtils.getString(MyApp.getmContext(), PrefUtils.USER_PWD, "");
        Map<String, String> map = new HashMap<>();
        map.put("loginName", user_account);
        map.put("password", user_pwd);
        map.put("application_code", "1");
        Call<ResponseData<LoginBean>> call = OkGo.<ResponseData<LoginBean>>post(HttpUrl.LOGIN)
                .upJson(new JSONObject(map))
                .converter(new JsonConvert<ResponseData<LoginBean>>() {
                })
                .adapt();
        try {
            com.lzy.okgo.model.Response<ResponseData<LoginBean>> response = call.execute();
            newToken = response.body();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newToken.data.token;
    }

    /**
     * 根据Response，判断Token是否失效
     *
     * @return
     */
    private boolean isTokenExpired(String resultStr) {
        RequestCode requestCode = new Gson().fromJson(resultStr, RequestCode.class);
        //err==3  token过期
        if (requestCode.retCode == 20003) {
            Logger.e("Token登录过期了");
            return true;
        }

        return false;
    }

    class RequestCode {
        /**
         * code : 0
         * data : {}
         * message : success
         */

        public int retCode;
        public String retMsg;
    }


}
